package com.zhuzi.guicollect.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;

import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: MI
 * @Date: 2021/10/25/20:42
 * @Description:
 */
@Slf4j
public class SysUtils {
    public static void sleep(int delay) {
        try {
            TimeUnit.SECONDS.sleep(delay);
        } catch (InterruptedException e) {
        }
    }

    public static boolean isNumber(String str) {
        try {
            new BigDecimal(str);
            return true;
        } catch (Exception e) {
        }
        return false;
    }

    public static String getLoginStr() {
        if (StringUtils.isBlank(loginStr)) {
            init();
        }
        return loginStr;
    }

    public static volatile String loginStr = "";
    /**
     * 访问的关键字
     */
    public static final String COOKIE_KEY_NAME = "kbzw__user_login";

    private static void init() {
        String userName = IniUtils.read("default", "userName");
        String userPwd = IniUtils.read("default", "userPwd");
        login(userName, userPwd);
        IniUtils.update("default", "lastLoginTime", LocalDate.now().format(DateTimeFormatter.ISO_LOCAL_DATE));
    }

    private static boolean login(String userName, String userPwd) {
        String urlLogin = "https://www.jisilu.cn/account/ajax/login_process/";
        Map<String, String> loginDataMap = new HashMap<>(4);
        loginDataMap.put("return_url", "https://www.jisilu.cn/");
        //my
        loginDataMap.put("user_name", userName);
        loginDataMap.put("password", userPwd);
        loginDataMap.put("net_auto_login", "1");
        loginDataMap.put("_post_type", "ajax");
        loginDataMap.put("aes", "1");
        final Connection connect = Jsoup.connect(urlLogin);
        try {
            Connection.Response response = connect.method(Connection.Method.POST).ignoreContentType(true)
                    .ignoreHttpErrors(true)
                    .data(loginDataMap)
                    .followRedirects(false)
                    .execute();
            System.out.println(response.statusMessage());
            System.out.println(response.body());
            final Map<String, String> cookies = response.cookies();
            JSONObject jsonObject = JSONObject.parseObject(response.body());
            String err = jsonObject.getString("err");
            if (StringUtils.isBlank(err)) {
                loginStr = COOKIE_KEY_NAME + "=" + cookies.get(COOKIE_KEY_NAME);
                //{"rsm":null,"errno":-1,"err":"用户名或口令无效"}
                //{"rsm":{"url":"https:\/\/www.jisilu.cn\/"},"errno":1,"err":null}
                log.info("登陆访问~成功：{} {}", userName, loginStr);
                //TODO 保存loginStr到 ini文件
                IniUtils.update("user", "userLoginStr", loginStr);
                IniUtils.update("user", "loginTime", LocalDate.now().toString());
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error("登陆访问失败:{}", e);
        }
        return false;
    }

    private volatile static boolean login;

    public static void main1(String[] args) {
        System.out.println(LocalDate.now().format(DateTimeFormatter.ISO_LOCAL_DATE));
        System.out.println(isDirExit("d:/"));
        login("a98b45b3dec80716d168b1df35a6c981", "720e41c74690d6f5eff4e990ca371dad");
    }

    public static boolean isDirExit(String pathStr) {
        try {
            Path path = Paths.get(pathStr);
            if (path.toFile().isDirectory()) {
                return true;
            }
        } catch (Exception e) {
        }
        return false;

    }


    /**
     * 初始化尝试登陆
     */
    public static void tryLogin() {
        String loginStrIni = IniUtils.read("user", "userLoginStr");
        String loginTime = IniUtils.read("user", "loginTime");
        if (!StringUtils.isAnyBlank(loginStrIni, loginTime)) {
            LocalDate lastLogin = LocalDate.parse(loginTime).plusDays(5);
            if (lastLogin.isAfter(LocalDate.now())) {
                SysUtils.loginStr = loginStrIni;
                if (!HttpUtils.isLogin()) {
                    SysUtils.loginStr = "";
                    return;
                }
                log.info("使用上次登录痕迹");
                SysUtils.login = true;
            }
        }
    }

    public static boolean userLogin(String user, String pwd) {
        JSrun.UserNamePwd userEnc = JSrun.exect(user, pwd);
        login = login(userEnc.getEncName(), userEnc.getEncPwd());
        return login;
    }

    public static boolean isLogin() {
        return login;
    }

    public static void main(String[] args) {
        LocalDate now = LocalDate.now().plusDays(1);
        System.out.println(now.toString());
        LocalDate parse = LocalDate.parse(now.toString());
        System.out.println(parse);

    }

}
